package com.bz.xtcx.manager.task;

import com.bz.xtcx.manager.entity.*;
import com.bz.xtcx.manager.mapper.*;
import com.bz.xtcx.manager.utils.SmsSender;
import com.bz.xtcx.manager.utils.WzEncryptUtil;
import com.bz.xtcx.manager.utils.WzStrUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.jms.annotation.JmsListener;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

import javax.crypto.SecretKey;
import javax.mail.MessagingException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeUtility;

@Component
public class CmsMeetingNoticeService {

    /** 日志. */
    private final Logger logger = LoggerFactory.getLogger(CmsMeetingNoticeService.class);

    @Value("${wzsetting.meeting-url}")
    private String meetingUrl;

    @Value("${wzsetting.zjk-url}")
    private String zjkUrl;

    @Value("${wzsetting.xqk-url}")
    private String xqkUrl;

    @Value("${wzsetting.cgk-url}")
    private String cgkUrl;

    @Value("${wzsetting.fwk-url}")
    private String fwkUrl;

    @Value("${wzsetting.index-url}")
    private String indexUrl;

    @Value("${mail.fromMail.addr}")
    private String mailFromAddr;

    @Value("${mail.fromMail.addr-alias}")
    private String mailFromAlias;

    @Autowired
    private JavaMailSender mailSender;

    @Autowired
    private CmsMeetingMapper cmsMeetingMapper;
    
    @Autowired
	private LibExpertMapper libExpertMapper;
    
    @Autowired
	private LibServiceMapper libServiceMapper;
    
    @Autowired
	private LibReqMapper libReqMapper;
	
	@Autowired
	private LibResMapper libResMapper;

	@Autowired
	private BusUserMapper busUserMapper;

	@Autowired
	private SmsSender smsSender;

    /**
     * 发起申请短信通知处理.
     */
    @JmsListener(destination = "jmrh_req_meeting_mobile_queue")
    public void reqMeetingMobileNotice(CmsMeeting data) {
        logger.info("对接[" + data.getCode() + "]发送请求短信开始");
        boolean djTargetIsOk = false;
        try {
//            CmsMeeting data = JSONObject.parseObject(dataStr, CmsMeeting.class);
            // 根据fromer从用户表中查询用户信息，获得名称
            String fromerName = null;
            if (WzStrUtil.isNotBlank(data.getFromerContactsName())) {
                fromerName = data.getFromerName();
            } else {
                BusUser bu = busUserMapper.findById(data.getFromer());
                if (null == bu || WzStrUtil.isBlank(bu.getName())) {
                    logger.error("对接发起人信息不完整");
                }
                fromerName = bu.getName();
            }

            // 关联查询数据
            NoticeTargetInfo noticeTargetVo = makeNoticeTarget(data.getTypeId(), data.getApplicationContentId());
            if (null == noticeTargetVo) {
                logger.error("对接[" + data.getCode() + "]未获得接收人手机号信息");
                CmsMeeting updVo = new CmsMeeting();
                updVo.setId(data.getId());
                updVo.setReqMobileCnt(4);
                cmsMeetingMapper.updateByPrimaryKeySelective(updVo);
                return;
            }
            // 组织消息
            String sendMsg = null;
            sendMsg = makeReqMsg(data.getTypeId(), noticeTargetVo.getTargetName(), fromerName, noticeTargetVo.getTargetAppName(), data.getCode(), true);
            if (WzStrUtil.isNotBlank(sendMsg) && (-1 == data.getCheckStatus() || 0 == data.getCheckStatus())) {
                if (!WzStrUtil.isMobile(noticeTargetVo.getTargetMobile())) {
                    logger.error("目标手机号[" + noticeTargetVo.getTargetMobile() + "]格式错误，发送失败");
                    CmsMeeting updVo = new CmsMeeting();
                    updVo.setId(data.getId());
                    updVo.setReqMobileCnt(4);
                    cmsMeetingMapper.updateByPrimaryKeySelective(updVo);
                } else {
                    // 发送短信
                    boolean isSendOK = smsSender.sendSms(noticeTargetVo.getTargetMobile(), sendMsg);
                    // 更新结果
                    CmsMeeting updVo = new CmsMeeting();
                    updVo.setId(data.getId());
                    updVo.setReqMobileCnt(data.getReqMobileCnt() + 1);
                    // 如果短信发送成功
                    if (isSendOK) {
                        updVo.setCheckStatus(0);
                        updVo.setReqMobileStatus(1);
                    } else {
                        updVo.setReqMobileCnt(4);
                    }
                    cmsMeetingMapper.updateByPrimaryKeySelective(updVo);
                }
            }
        } catch (Exception e) {
            logger.error("对接[" + data.getCode() + "]发送请求短信时发生异常.", e);
        }
        logger.info("对接[" + data.getCode() + "]发送请求短信结束");
    }

    /**
     * 发起申请邮件通知处理.
     */
    @JmsListener(destination = "jmrh_req_meeting_email_queue")
    public void reqMeetingMailNotice(CmsMeeting data) {
        logger.info("对接[" + data.getCode() + "]发送请求邮件开始");
        try {
            // 根据fromer从用户表中查询用户信息，获得名称
            String fromerName = null;
            if (WzStrUtil.isNotBlank(data.getFromerContactsName())) {
                fromerName = data.getFromerName();
            } else {
                BusUser bu = busUserMapper.findById(data.getFromer());
                if (null == bu || WzStrUtil.isBlank(bu.getName())) {
                    logger.error("对接发起人信息不完整");
                }
                fromerName = bu.getName();
            }
            // 关联查询数据
            NoticeTargetInfo noticeTargetVo = makeNoticeTarget(data.getTypeId(), data.getApplicationContentId());
            if (null == noticeTargetVo) {
                logger.error("对接[" + data.getCode() + "]未获得接收人邮箱信息");
                CmsMeeting updVo = new CmsMeeting();
                updVo.setId(data.getId());
                updVo.setReqMailCnt(4);
                cmsMeetingMapper.updateByPrimaryKeySelective(updVo);
            }
            // 组织消息
            String sendMsg = null;
            sendMsg = makeReqMsg(data.getTypeId(), noticeTargetVo.getTargetName(), fromerName, noticeTargetVo.getTargetAppName(), data.getCode(), false);
            if (WzStrUtil.isNotBlank(sendMsg) && (-1 == data.getCheckStatus() || 0 == data.getCheckStatus())) {
                // 发送邮件
                String sj = "您有一个来自苏南自创区国家军民科技协同创新平台的对接申请";
                if (!WzStrUtil.isEmail(noticeTargetVo.getTargetEmail())) {
                    logger.error("目标邮箱[" + noticeTargetVo.getTargetEmail() + "]格式错误，发送失败");
                    CmsMeeting updVo = new CmsMeeting();
                    updVo.setId(data.getId());
                    updVo.setReqMailCnt(4);
                    cmsMeetingMapper.updateByPrimaryKeySelective(updVo);
                } else {
                    boolean isSendOk = sendHtmlEmail(noticeTargetVo.getTargetEmail(), sj, sendMsg);
                    // 更新结果
                    CmsMeeting updVo = new CmsMeeting();
                    updVo.setId(data.getId());
                    updVo.setReqMailCnt(data.getReqMailCnt() + 1);
                    // 如果邮件发送成功
                    if (isSendOk) {
                        updVo.setCheckStatus(0);
                        updVo.setReqMailStatus(1);
                    } else {
                        updVo.setReqMailCnt(4);
                    }
                    cmsMeetingMapper.updateByPrimaryKeySelective(updVo);
                }
            }
        } catch (Exception e) {
            logger.error("对接[" + data.getCode() + "]发送请求邮件时发生异常.", e);
        }
        logger.info("对接[" + data.getCode() + "]发送请求邮件结束");
    }

    /**
     * 响应申请短信通知处理.
     */
    @JmsListener(destination = "jmrh_resp_meeting_mobile_queue")
    public void respMeetingMobileNotice(CmsMeeting data) {
        logger.info("对接[" + data.getCode() + "]发送回复短信开始");
        try {
            // 根据fromer从用户表中查询用户信息，获得名称
            String fromerName = null;
            String fromerMobile = null;
            if (WzStrUtil.isNotBlank(data.getFromerContactsName()) && WzStrUtil.isMobile(data.getFromerContactsPhone())) {
                fromerName = data.getFromerName();
                fromerMobile = data.getFromerContactsPhone();
            } else {
                BusUser bu = busUserMapper.findById(data.getFromer());
                if (null == bu || WzStrUtil.isBlank(bu.getName())) {
                    logger.error("对接发起人信息不完整");
                    return;
                }
                fromerName = bu.getName();
                fromerMobile = bu.getCellphone();
            }
            if (!WzStrUtil.isMobile(fromerMobile)) {
                logger.error("对接[\" + data.getCode() + \"]未获得发起人手机号信息或手机号格式错误");
                // 更新结果
                CmsMeeting updVo = new CmsMeeting();
                updVo.setId(data.getId());
                updVo.setRespMobileCnt(4);
                cmsMeetingMapper.updateByPrimaryKeySelective(updVo);
                return;
            }
            // 关联查询数据
            NoticeTargetInfo noticeTargetVo = makeNoticeTarget(data.getTypeId(), data.getApplicationContentId());
            // 组织消息
            String sendMsg = null;
            if (1 == data.getCheckStatus()) {
                sendMsg = makeRespAgreeMsg(data.getTypeId(), noticeTargetVo.getTargetName(), fromerName, data.getApplicationContentId(), true);
            } else if (2 == data.getCheckStatus()) {
                sendMsg = makeRespRefuseMsg(data.getTypeId(), noticeTargetVo.getTargetName(), fromerName, true);
            } else if (3 == data.getCheckStatus()) {
                sendMsg = makeRespLostMsg(data.getTypeId(), noticeTargetVo.getTargetName(), fromerName, true);
            }
            if (WzStrUtil.isNotBlank(sendMsg) && (1 == data.getCheckStatus() || 2 == data.getCheckStatus() || 3 == data.getCheckStatus())) {
                if (!WzStrUtil.isMobile(noticeTargetVo.getTargetMobile())) {
                    logger.error("目标手机号[" + fromerMobile + "]格式错误，发送失败");
                    CmsMeeting updVo = new CmsMeeting();
                    updVo.setId(data.getId());
                    updVo.setRespMobileCnt(4);
                    cmsMeetingMapper.updateByPrimaryKeySelective(updVo);
                } else {
                    // 发送短信
                    boolean isSendOK = smsSender.sendSms(fromerMobile, sendMsg);
                    // 更新结果
                    CmsMeeting updVo = new CmsMeeting();
                    updVo.setId(data.getId());
                    updVo.setRespMobileCnt(data.getRespMobileCnt() + 1);
                    // 如果短信发送成功
                    if (isSendOK) {
                        updVo.setRespMobileStatus(1);
                    } else {
                        updVo.setRespMobileCnt(4);
                    }
                    cmsMeetingMapper.updateByPrimaryKeySelective(updVo);
                }
            }
        } catch (Exception e) {
            logger.error("对接[" + data.getCode() + "]发送回复短信时发生异常.", e);
        }
        logger.info("对接[" + data.getCode() + "]发送回复短信结束");
    }

    /**
     * 响应申请邮件通知处理.
     */
    @JmsListener(destination = "jmrh_resp_meeting_email_queue")
    public void respMeetingMailNotice(CmsMeeting data) {
        logger.info("对接[" + data.getCode() + "]发送回复邮件开始");
        try {
            // 根据fromer从用户表中查询用户信息，获得名称
            String fromerName = null;
            String fromerEmail = null;
            if (WzStrUtil.isNotBlank(data.getFromerContactsName()) && WzStrUtil.isEmail(data.getFromerContactsMail())) {
                fromerName = data.getFromerName();
                fromerEmail = data.getFromerContactsMail();
            } else {
                BusUser bu = busUserMapper.findById(data.getFromer());
                if (null == bu || WzStrUtil.isBlank(bu.getName())) {
                    logger.error("对接发起人信息不完整");
                    return;
                }
                fromerName = bu.getName();
                fromerEmail = bu.getEmail();
            }
            if (!WzStrUtil.isEmail(fromerEmail)) {
                logger.error("对接[\" + data.getCode() + \"]未获得发起人邮箱信息或邮箱格式错误");
                // 更新结果
                CmsMeeting updVo = new CmsMeeting();
                updVo.setId(data.getId());
                updVo.setRespMailCnt(4);
                cmsMeetingMapper.updateByPrimaryKeySelective(updVo);
                return;
            }
            // 关联查询数据
            NoticeTargetInfo noticeTargetVo = makeNoticeTarget(data.getTypeId(), data.getApplicationContentId());
            // 组织消息
            String sendMsg = null;
            if (1 == data.getCheckStatus()) {
                sendMsg = makeRespAgreeMsg(data.getTypeId(), noticeTargetVo.getTargetName(), fromerName, data.getApplicationContentId(), false);
            } else if (2 == data.getCheckStatus()) {
                sendMsg = makeRespRefuseMsg(data.getTypeId(), noticeTargetVo.getTargetName(), fromerName, false);
            } else if (3 == data.getCheckStatus()) {
                sendMsg = makeRespLostMsg(data.getTypeId(), noticeTargetVo.getTargetName(), fromerName, false);
            }
            if (WzStrUtil.isNotBlank(sendMsg) && (1 == data.getCheckStatus() || 2 == data.getCheckStatus() || 3 == data.getCheckStatus())) {
                // 发送邮件
                String sj = "您有一个来自苏南自创区国家军民科技协同创新平台对接申请的回复";
                if (!WzStrUtil.isEmail(fromerEmail)) {
                    logger.error("目标邮箱[" + fromerEmail + "]格式错误，发送失败");
                    CmsMeeting updVo = new CmsMeeting();
                    updVo.setId(data.getId());
                    updVo.setRespMailCnt(4);
                    cmsMeetingMapper.updateByPrimaryKeySelective(updVo);
                } else {
                    boolean isSendOk = sendHtmlEmail(fromerEmail, sj, sendMsg);
                    // 更新结果
                    CmsMeeting updVo = new CmsMeeting();
                    updVo.setId(data.getId());
                    updVo.setRespMailCnt(data.getRespMailCnt() + 1);
                    // 如果邮件发送成功
                    if (isSendOk) {
                        updVo.setRespMailStatus(1);
                    } else {
                        updVo.setRespMailCnt(4);
                    }
                    cmsMeetingMapper.updateByPrimaryKeySelective(updVo);
                }
            }
        } catch (Exception e) {
            logger.error("对接[" + data.getCode() + "]发送回复邮件时发生异常.", e);
        }
        logger.info("对接[" + data.getCode() + "]发送回复邮件结束");
    }

    // modify by wangtao on 20190103 for 对接链接参数需不可预测,对参数进行加密 start
    private String encryptTaCd(String taCd) {
        if (WzStrUtil.isBlank(taCd)) {
            return "";
        }
        try {
            SecretKey sk = WzEncryptUtil.genAesKey();
            byte[] taCdBytes = WzEncryptUtil.encryptAES(sk, taCd.getBytes("utf-8"));
            String encryptTaCdBase64Str = WzEncryptUtil.byteArrToBase64(taCdBytes);
            String encryptTaCdStr = WzEncryptUtil.encryptHex(encryptTaCdBase64Str, "utf-8");
            if (WzStrUtil.isBlank(encryptTaCdStr)) {
                return taCd;
            } else {
                return encryptTaCdStr;
            }
        } catch (Exception ex) {
            return taCd;
        }
    }

    private String makeReqMsg(Integer typeId, String tNm, String fNm, String taNm, String taCd, boolean isMobile) {
        String sMsg = null;
        String encTaCd = encryptTaCd(taCd);
        if (0 == typeId) {
            sMsg = "尊敬的"
                    + tNm
                    + "专家，"
                    + fNm
                    + "对您的相关研究成果感兴趣，"
                    + "通过苏南自创区国家军民科技协同创新平台请求与您对接。请点击 "
                    + (isMobile ? (meetingUrl + encTaCd) : ("<a href=\"" + meetingUrl + encTaCd + "\">对接详情</a>"))
                    + " 查看对接详情并回复。";
        } else if (1 == typeId) {
            sMsg = "尊敬的"
                    + tNm
                    + "，"
                    + fNm
                    + "通过苏南自创区国家军民科技协同创新平台请求与您们提出的"
                    + taNm
                    + "需求对接。请点击 "
                    + (isMobile ? (meetingUrl + encTaCd) : ("<a href=\"" + meetingUrl + encTaCd + "\">对接详情</a>"))
                    + " 查看对接详情并回复。";
        } else if (2 == typeId) {
            sMsg = "尊敬的"
                    + tNm
                    + "，"
                    + fNm
                    + "对您团队研发的"
                    + taNm
                    + "成果感兴趣，"
                    + "并通过苏南自创区国家军民科技协同创新平台请求与您对接。"
                    + "请点击 "
                    + (isMobile ? (meetingUrl + encTaCd) : ("<a href=\"" + meetingUrl + encTaCd + "\">对接详情</a>"))
                    + " 查看对接详情并回复。";
        } else if (3 == typeId) {
            sMsg = "尊敬的"
                    + tNm
                    + "，"
                    + fNm
                    + "对您提供的"
                    + taNm
                    + "服务感兴趣，"
                    + "并通过苏南自创区国家军民科技协同创新平台请求与您对接。"
                    + "请点击 "
                    + (isMobile ? (meetingUrl + encTaCd) : ("<a href=\"" + meetingUrl + encTaCd + "\">对接详情</a>"))
                    + " 查看对接详情并回复。";
        }
        return sMsg;
    }
    // modify by wangtao on 20190103 for 对接链接参数需不可预测,对参数进行加密 end

    private String makeRespAgreeMsg(Integer typeId, String tNm, String fNm, String taCd, boolean isMobile) {
        String sMsg = null;
        if (0 == typeId) {
            sMsg = "尊敬的"
                    + fNm
                    + "，"
                    + tNm
                    + "专家同意您的对接请求，请您登录苏南自创区国家军民科技协同创新平台 "
                    + (isMobile ? (zjkUrl + taCd) : ("<a href=\"" + zjkUrl + taCd + "\">专家详情</a>"))
                    + " 查看专家的联系方式以及其他相关信息。";
        } else if (1 == typeId) {
            sMsg = "尊敬的"
                    + fNm
                    + "，"
                    + tNm
                    + "同意您的对接请求，请您登录苏南自创区国家军民科技协同创新平台 "
                    + (isMobile ? (xqkUrl + taCd) : ("<a href=\"" + xqkUrl + taCd + "\">需求详情</a>"))
                    + " 查看需求方的联系方式以及其他相关信息。";
        } else if (2 == typeId) {
            sMsg = "尊敬的"
                    + fNm
                    + "，"
                    + tNm
                    + "同意您的对接请求，请您登录苏南自创区国家军民科技协同创新平台 "
                    + (isMobile ? (cgkUrl + taCd) : ("<a href=\"" + cgkUrl + taCd + "\">成果详情</a>"))
                    + " 查看成果提供方的联系方式以及其他相关信息。";
        } else if (3 == typeId) {
            sMsg = "尊敬的"
                    + fNm
                    + "，"
                    + tNm
                    + "同意您的对接请求，请您登录苏南自创区国家军民科技协同创新平台 "
                    + (isMobile ? (fwkUrl + "?id=" + taCd) : ("<a href=\"" + fwkUrl + taCd + "\">服务机构详情</a>"))
                    + " 查看服务机构的联系方式以及其他相关信息。";
        }
        return sMsg;
    }

    private String makeRespRefuseMsg(Integer typeId, String tNm, String fNm, boolean isMobile) {
        String sMsg = null;
        if (0 == typeId) {
            sMsg = "尊敬的"
                    + fNm
                    + "，很遗憾，"
                    + tNm
                    + "拒绝您的对接请求。您可以访问苏南自创区国家军民科技协同创新平台 "
                    + (isMobile ? indexUrl : ("<a href=\"" + indexUrl + "\">协同创新栏目</a>"))
                    + " 查看其他专家资源。";
        } else if (1 == typeId) {
            sMsg = "尊敬的"
                    + fNm
                    + "，很遗憾，"
                    + tNm
                    + "拒绝您的对接请求。您可以访问苏南自创区国家军民科技协同创新平台 "
                    + (isMobile ? indexUrl : ("<a href=\"" + indexUrl + "\">协同创新栏目</a>"))
                    + " 查看其他需求。";
        } else if (2 == typeId) {
            sMsg = "尊敬的"
                    + fNm
                    + "，很遗憾，"
                    + tNm
                    + "拒绝您的对接请求。您可以访问苏南自创区国家军民科技协同创新平台 "
                    + (isMobile ? indexUrl : ("<a href=\"" + indexUrl + "\">协同创新栏目</a>"))
                    + " 查看其他成果。";
        } else if (3 == typeId) {
            sMsg = "尊敬的"
                    + fNm
                    + "，很遗憾，"
                    + tNm
                    + "拒绝您的对接请求。您可以访问苏南自创区国家军民科技协同创新平台 "
                    + (isMobile ? indexUrl : ("<a href=\"" + indexUrl + "\">协同创新栏目</a>"))
                    + " 查看其他服务资源。";
        }
        return sMsg;
    }

    private String makeRespLostMsg(Integer typeId, String tNm, String fNm, boolean isMobile) {
        String sMsg = null;
        if (0 == typeId) {
            sMsg = "尊敬的"
                    + fNm
                    + "，很遗憾，"
                    + tNm
                    + "未回复您的对接请求。您可以访问苏南自创区国家军民科技协同创新平台 "
                    + (isMobile ? indexUrl : ("<a href=\"" + indexUrl + "\">" + indexUrl + "</a>"))
                    + " 查看其他专家资源。";
        } else if (1 == typeId) {
            sMsg = "尊敬的"
                    + fNm
                    + "，很遗憾，"
                    + tNm
                    + "未回复您的对接请求。您可以访问苏南自创区国家军民科技协同创新平台 "
                    + (isMobile ? indexUrl : ("<a href=\"" + indexUrl + "\">" + indexUrl + "</a>"))
                    + " 查看其他需求。";
        } else if (2 == typeId) {
            sMsg = "尊敬的"
                    + fNm
                    + "，很遗憾，"
                    + tNm
                    + "未回复您的对接请求。您可以访问苏南自创区国家军民科技协同创新平台 "
                    + (isMobile ? indexUrl : ("<a href=\"" + indexUrl + "\">" + indexUrl + "</a>"))
                    + " 查看其他成果。";
        } else if (3 == typeId) {
            sMsg = "尊敬的"
                    + fNm
                    + "，很遗憾，"
                    + tNm
                    + "未回复您的对接请求。您可以访问苏南自创区国家军民科技协同创新平台 "
                    + (isMobile ? indexUrl : ("<a href=\"" + indexUrl + "\">" + indexUrl + "</a>"))
                    + " 查看其他服务资源。";
        }
        return sMsg;
    }

    private NoticeTargetInfo makeNoticeTarget(Integer typeId, String applicationContentId) {
        NoticeTargetInfo nti = null;
        if (0 == typeId) {
         	LibExpert lib = libExpertMapper.findById(applicationContentId);
        	if(lib != null) {
        		nti = new NoticeTargetInfo();
        		nti.setTargetAppName(lib.getName());
        		nti.setTargetName(lib.getName());
        		nti.setTargetMobile(lib.getCellphone());
        		nti.setTargetEmail(lib.getEmail());
        	}
        } else if (1 == typeId) {
            // 根据application_content_id从需求库查询需求信息，获得需求名称及联系人电话和邮箱
        	LibRequirements lib = libReqMapper.findById(applicationContentId);
        	if(lib != null) {
        		nti = new NoticeTargetInfo();
        		nti.setTargetAppName(lib.getReqName());//需求名
                if (WzStrUtil.isNotBlank(lib.getFzname2())) {
                    nti.setTargetName(lib.getFzname2());
                    if (WzStrUtil.isMobile(lib.getFzphone2()) || WzStrUtil.isEmail(lib.getFzemail2())) {
                        nti.setTargetMobile(lib.getFzphone2());
                        nti.setTargetEmail(lib.getFzemail2());
                    }
                } else if (WzStrUtil.isNotBlank(lib.getFzname())) {
                    nti.setTargetName(lib.getFzname());
                    if (WzStrUtil.isMobile(lib.getFzphone()) || WzStrUtil.isEmail(lib.getFzemail())) {
                        nti.setTargetMobile(lib.getFzphone());
                        nti.setTargetEmail(lib.getFzemail());
                    }
                }
        	}
        } else if (2 == typeId) {
            // 根据application_content_id从成果库查询成果信息，获得成果名称及联系人电话和邮箱
        	LibResults lib = libResMapper.findById(applicationContentId);
        	if(lib != null) {
        		nti = new NoticeTargetInfo();
        		nti.setTargetAppName(lib.getResName());
                if (WzStrUtil.isNotBlank(lib.getFzname2())) {
                    nti.setTargetName(lib.getFzname2());
                    if (WzStrUtil.isMobile(lib.getFzphone2()) || WzStrUtil.isEmail(lib.getFzemail2())) {
                        nti.setTargetMobile(lib.getFzphone2());
                        nti.setTargetEmail(lib.getFzemail2());
                    }
                } else if (WzStrUtil.isNotBlank(lib.getFzname())) {
                    nti.setTargetName(lib.getFzname());
                    if (WzStrUtil.isMobile(lib.getFzphone()) || WzStrUtil.isEmail(lib.getFzemail())) {
                        nti.setTargetMobile(lib.getFzphone());
                        nti.setTargetEmail(lib.getFzemail());
                    }
                }
        	}
        } else if (3 == typeId) {
            // 根据application_content_id从服务库查询服务信息，获得服务名称及联系人电话和邮箱
        	LibServices lib = libServiceMapper.findById(applicationContentId);
        	if(lib != null) {
        		nti = new NoticeTargetInfo();
        		nti.setTargetAppName(lib.getName());
                nti.setTargetName(lib.getLinkman());
                nti.setTargetMobile(lib.getLxmobile());
                nti.setTargetEmail(lib.getLxemail());
        	}
        }
        return nti;
    }

    /**
     * 发送邮件.
     * @param to 目标
     * @param subject 主题
     * @param content 内容
     * @return true：发送成功；false：发送失败
     */
    public boolean sendHtmlEmail(String to, String subject, String content) {
        // 创建一个MINE消息
        MimeMessage message = mailSender.createMimeMessage();
        try {
            // true 表示需要创建一个Multipart Message
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            String addrNick = checkFromAlias();
            if (WzStrUtil.isNotBlank(addrNick)) {
                helper.setFrom(new InternetAddress(addrNick + " <" + mailFromAddr + ">"));
            } else {
                helper.setFrom(mailFromAddr);
            }
            helper.setTo(to);
            helper.setSubject(subject);
            helper.setText(content, true);
            mailSender.send(message);
            logger.info("邮件发送成功");
        } catch (MessagingException e) {
            logger.error("发送邮件时发生异常！", e);
            return false;
        }
        return true;
    }

    /**
     * 检查发送人别名.
     * @return 别名
     */
    private String checkFromAlias() {
        String ank = mailFromAlias;
        if (WzStrUtil.isNotBlank(ank)) {
            try {
                ank = MimeUtility.encodeText(ank);
            } catch (Exception ex) {
                logger.error("邮件发送地址昵称转换失败", ex);
                ank = null;
            }
        }
        return ank;
    }
}
